/**  
* @Title: AuthServiceImpl.java
* @Package cn.com.gzheroli.bfw.service.impl  
* @Description: TODO(用一句话描述该文件做什么)  
* @author 李长荣  
* @date 2017年6月8日  
* @version V1.0  
*/
package cn.com.gzheroli.bfw.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.ibatis.jdbc.SQL;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.gzheroli.auth.service.TSDataruleService;
import cn.com.gzheroli.bfw.pojo.base.TSDepart;
import cn.com.gzheroli.bfw.pojo.base.TSUser;
import cn.com.gzheroli.bfw.service.AuthService;
import cn.com.gzheroli.cache.SpringRedisCache;
import cn.com.gzheroli.core.common.service.CommonService;
import cn.com.gzheroli.core.util.MenuBean;
import cn.com.gzheroli.core.util.mybatis.SqlMapper;
import cn.com.gzheroli.tag.vo.vue.VueTreeBean;

/**  
* @ClassName:AuthServiceImpl 
* @Description: TODO(这里用一句话描述这个类的作用)  
* @author 李长荣  
* @date 2017年6月8日  
*/
@Service("authService")
public class AuthServiceImpl implements AuthService{
	/**
	 * 数据库类型
	 */
	public static final String DATABSE_TYPE_MYSQL ="MySQL";
	public static final String DATABSE_TYPE_POSTGRE ="postgresql";
	public static final String DATABSE_TYPE_ORACLE ="oracle";
	public static final String DATABSE_TYPE_SQLSERVER ="sqlserver";
	private static final Logger logger = Logger.getLogger(AuthServiceImpl.class);
	@Resource
	private CommonService commonService;
	
	@Autowired
    private  SpringRedisCache cache;
	@Autowired
	private TSDataruleService dataruleService;
	
	@Override
	public List<Map<String, Object>> getAuthMenuOperation(TSUser user, String menuId,String path) {
		Map para=new HashMap();
		para.put("userId", user.getId());
		para.put("menuId", menuId);
		para.put("path", path);
		SQL sql=new SQL();
		sql.SELECT("rf.OPERATION");
		sql.FROM("T_S_ROLE_FUNCTION rf");
		sql.FROM("T_S_ROLE_USER ru");
		sql.FROM("T_S_FUNCTION f");
		if(null!=menuId&&!menuId.trim().equals(""))
			sql.WHERE("rf.FUNCTION_ID=#{menuId}");
		if(null!=path&&!path.trim().equals(""))
			sql.WHERE("f.FUNCTION_URL=#{path}");
		sql.WHERE("rf.ROLE_ID=ru.ROLE_ID");
		sql.WHERE("rf.FUNCTION_ID=f.ID");
		sql.WHERE("ru.USER_ID=#{userId}");
		return commonService.findForJdbc(sql.toString(), para);
	}

	@Override
	public List<Map<String, Object>> getAuthMenu(TSUser user,String parentId) {
		List<Map<String,Object>> authList=null;
		if(parentId!=null&&!parentId.trim().equals(""))
			authList=getMenu(user.getId(),parentId,null);
		else
			authList=getMenu(user.getId(),"",null);
		for(Map<String,Object> auth:authList){
			String id=auth.get("id").toString();
			List<Map<String,Object>> childList = new ArrayList<Map<String,Object>>();
			childList=getChild(user.getId(),childList,id);
			if(childList!=null&&!childList.isEmpty())
				auth.put("leaf", false);
			else
				auth.put("leaf", true);
			auth.put("children", childList);
		}
		return authList;
		
	}
	private List<Map<String,Object>> getMenu(String userId,String parentId,String isMenu){
		Map para=new HashMap();
		para.put("userId", userId);
		para.put("parentId", parentId);
		para.put("isMenu", isMenu);
		String dataBaseType=cache.getCache("dataBaseType", String.class);
		SQL sql=new SQL();
		sql.SELECT("distinct f.ID,f.FUNCTION_NAME name,f.COMPONENT_NAME component,f.FUNCTION_URL path,f.FUNCTION_ORDER ,f.FRONT_ICON icon_Cls,f.META,f.IS_MENU,f.IS_FRONT ");
		sql.FROM("T_S_ROLE_FUNCTION rf");
		sql.FROM("T_S_FUNCTION f");
		sql.FROM("T_S_ROLE_USER ru");
		sql.WHERE("rf.FUNCTION_ID=f.ID");
		sql.WHERE("rf.ROLE_ID=ru.ROLE_ID");
		sql.WHERE("ru.USER_ID=#{userId}");
		if(null==parentId||parentId.trim().equals(""))
			sql.WHERE("f.PARENT_ID is null");
		else
			sql.WHERE("f.PARENT_ID=#{parentId}");
		if(isMenu!=null&&!isMenu.trim().equals(""))
			sql.WHERE("f.IS_MENU=#{isMenu}");
		if(dataBaseType.indexOf(DATABSE_TYPE_MYSQL)!=-1){
			sql.ORDER_BY("cast(f.FUNCTION_ORDER as SIGNED) ");
		}else if(dataBaseType.indexOf(DATABSE_TYPE_ORACLE)!=-1) {
			sql.ORDER_BY("TO_NUMBER(f.FUNCTION_ORDER)");
		}
		return commonService.findForJdbc(sql.toString(), para);
	}
	private List<Map<String,Object>> getChild(String userId,List<Map<String,Object>> menuList,String parentId) {
		List<Map<String,Object>> list = getMenu(userId,parentId,null);
		if (list != null && !list.isEmpty())
			for (Map<String,Object> fun : list) {
				String id=fun.get("id").toString();
				List<Map<String,Object>> subList=getMenu(userId,id,null);
					if (subList==null|| subList.isEmpty()) {
						fun.put("children", new ArrayList());
						fun.put("leaf", true);
						menuList.add(fun);
					} else {
						List childList = new ArrayList();
						fun.put("children", getChild(userId,childList,id));
						fun.put("leaf", false);
						menuList.add(fun);
					}
			}
		return menuList;
	}
	public List<Map<String,Object>> getDepartList(Map dataMap,TSUser user) {
		SQL sql=new SQL();
		sql.SELECT("d.id ,d.DEPART_NAME text,d.PARENT_ID parentId,(select d2.DEPART_NAME from T_S_DEPART d2 where d.PARENT_ID=d2.id) parentName");
		sql.SELECT("d.description as src,( case when   (select count(1) from T_S_DEPART d3 where  d3.PARENT_ID=d.id) >0 then 'closed' else 'open'  end  ) as state");
		sql.FROM("T_S_DEPART d ");
		sql.WHERE("1=1");
		if(dataMap.containsKey("pid")&&dataMap.get("pid")!=null)
			sql.WHERE("d.PARENT_ID=#{pid}");
		else
			sql.WHERE(" (d.PARENT_ID='' or d.PARENT_ID is null) ");
		String sqlCondition=dataruleService.genSqlByModuleName("authDept","d",user);
		List<Map<String,Object>> deptList=commonService.findForJdbc(sql.toString()+sqlCondition, dataMap);
		return  deptList;
	}
	
	public List<VueTreeBean> getDepart( VueTreeBean comboTree,String departId,TSUser user){
		TSDepart dept=commonService.get(TSDepart.class, departId);
		String isNeedCheck=dept==null||dept.getIsNeedCheck()==null?"":dept.getIsNeedCheck();
		//String parentDepartId=dept.getParentId();
		String parentid=comboTree.getId()==null?"":comboTree.getId();
		Map para=new HashMap();
		String sql="select ID,DEPARTMENT_CODE,PARENT_ID,DEPART_NAME from T_S_DEPART d where d.status='1' and d.IS_NEED_CHECK='1' ";
		if(!parentid.equals(""))
			sql=sql+" and d.PARENT_ID=#{parentid}";
		else
			sql=sql+" and (d.PARENT_ID='' or d.PARENT_ID is null) ";
		/*else if(isNeedCheck.equals("")||isNeedCheck.equals("0"))
			sql=sql+" and (d.PARENT_ID='' or d.PARENT_ID is null)";
		else if(isNeedCheck.equals("1")&&parentid.equals("")){
			parentid=dept.getId();
			//sql=sql+" and ((d.PARENT_ID=#{parentid} and exists (select 1 from from T_S_DEPART d1 where d1.status='1' and d1.IS_NEED_CHECK='1' and d1.PARENT_ID=#{parentid}))";
			sql=sql+" and d.PARENT_ID=#{parentid}";
		}*/
			
		String sqlCondition=dataruleService.genSqlByModuleName("authDept","d",user);
		sql=sql+sqlCondition;
		para.put("parentid", parentid);
		List<Map<String, Object>> deptList=commonService.findForJdbc(sql,para);
		List<VueTreeBean> comboTrees = new ArrayList<VueTreeBean>();
		if(null!=deptList&&!deptList.isEmpty()){
			for(Map dep:deptList){
				VueTreeBean treebean = new VueTreeBean();
				treebean.setTitle(dep.get("departName").toString());
				treebean.setId(dep.get("id").toString());
				Long subDeptCount=commonService.getCountForJdbc("select count(*) from T_S_DEPART t where t.PARENT_ID='"+dep.get("id").toString()+"' and t.STATUS='1' and t.IS_NEED_CHECK='1'");
				if(subDeptCount>0){
					treebean.setExpand(false);
					List childList = new ArrayList();
					List<VueTreeBean> children=getChild(comboTree, treebean.getId(), user,childList);
					treebean.setNode(children);
				}else{
					treebean.setExpand(true);
					treebean.setNode(new ArrayList());
				}
					
				
				comboTrees.add(treebean);
	        }
		}else{
			VueTreeBean treebean = new VueTreeBean();
			treebean.setTitle(dept.getDepartName());
			treebean.setId(dept.getId());
			treebean.setExpand(true);
			treebean.setNode(new ArrayList());
			comboTrees.add(treebean);
		}
		
		return comboTrees;
	}
	
	public List<VueTreeBean> getAllDepart(VueTreeBean comboTree,String departId,TSUser user){
		TSDepart dept=commonService.get(TSDepart.class, departId);
		//String parentDepartId=dept.getParentId();
		String parentid=comboTree.getId()==null?"":comboTree.getId();
		Map para=new HashMap();
		String sql="select ID,DEPARTMENT_CODE,PARENT_ID,DEPART_NAME from T_S_DEPART d where d.status='1' and d.IS_NEED_CHECK='1' ";
		if(!parentid.equals(""))
			sql=sql+" and d.PARENT_ID=#{parentid}";
		else 
			sql=sql+" and (d.PARENT_ID='' or d.PARENT_ID is null) ";
		String sqlCondition=dataruleService.genSqlByModuleName("authDept","d",user);
		sql=sql+sqlCondition;
		sql=sql+"  order by d.LEVEL_NO ";
		para.put("parentid", parentid);
		
		List<Map<String, Object>> deptList=commonService.findForJdbc(sql,para);
		List<VueTreeBean> comboTrees = new ArrayList<VueTreeBean>();
		if(null!=deptList&&!deptList.isEmpty()){
			for(Map dep:deptList){
				VueTreeBean treebean = new VueTreeBean();
				treebean.setTitle(dep.get("departName").toString());
				treebean.setId(dep.get("id").toString());
				Long subDeptCount=commonService.getCountForJdbc("select count(*) from T_S_DEPART t where t.PARENT_ID='"+dep.get("id").toString()+"' and t.STATUS='1' and t.IS_NEED_CHECK='1'");
				if(subDeptCount>0){
					treebean.setExpand(false);
					List childList = new ArrayList();
					List<VueTreeBean> children=getChild(comboTree, treebean.getId(), user,childList);
					treebean.setNode(children);
				}else{
					treebean.setExpand(true);
					treebean.setNode(new ArrayList());
				}
					
				
				comboTrees.add(treebean);
	        }
		}else{
			VueTreeBean treebean = new VueTreeBean();
			treebean.setTitle(dept.getDepartName());
			treebean.setId(dept.getId());
			treebean.setExpand(true);
			treebean.setNode(new ArrayList());
			comboTrees.add(treebean);
		}
		
		return comboTrees;
	}
	
	private List<VueTreeBean> getChild(VueTreeBean comboTree,String departId,TSUser user,List<VueTreeBean> deptTeamList){
		TSDepart dept=commonService.get(TSDepart.class, departId);
		//String isNeedCheck=dept==null||dept.getIsNeedCheck()==null?"":dept.getIsNeedCheck();
		//String parentDepartId=dept.getParentId();
		String parentid=comboTree.getId()==null?"":comboTree.getId();
		Map para=new HashMap();
		String sql="select ID,DEPARTMENT_CODE,PARENT_ID,DEPART_NAME,(select count(1) from T_S_DEPART d3 where  d3.PARENT_ID=d.id) sub_Count from T_S_DEPART d where d.status='1'  ";
		if(!parentid.equals(""))
			sql=sql+" and d.PARENT_ID=#{parentid}";
		else
			sql=sql+" and (d.PARENT_ID='' or d.PARENT_ID is null) ";
		/*else if(isNeedCheck.equals("")||isNeedCheck.equals("0"))
			sql=sql+" and (d.PARENT_ID='' or d.PARENT_ID is null)";
		else if(isNeedCheck.equals("1")&&parentid.equals("")){
			parentid=dept.getId();
			sql=sql+" and d.PARENT_ID=#{parentid}";
		}*/
			
		String sqlCondition=dataruleService.genSqlByModuleName("authDept","d",user);
		sql=sql+sqlCondition;
		sql=sql+"  order by d.LEVEL_NO ";
		para.put("parentid", parentid);
		List<Map<String, Object>> deptList=commonService.findForJdbc(sql,para);
		//List<ComboTree> comboTrees = new ArrayList<ComboTree>();
		for(Map dep:deptList){
			VueTreeBean treebean = new VueTreeBean();
			treebean.setTitle(dep.get("departName").toString());
			treebean.setId(dep.get("id").toString());
			Long subDeptCount=(Long)dep.get("subCount");
			//Long subDeptCount=commonService.getCountForJdbc("select count(*) from T_S_DEPART t where t.PARENT_ID='"+dep.get("id").toString()+"' and t.STATUS='1' and t.IS_NEED_CHECK='1'");
			if(subDeptCount>0){
				treebean.setExpand(false);
				List childList = new ArrayList();
				List<VueTreeBean> children=getChild(comboTree, treebean.getId(), user,childList);
				treebean.setNode(children);
			}else{
				treebean.setExpand(true);
				treebean.setNode(new ArrayList());
			}
			deptTeamList.add(treebean);
        }
		return deptTeamList;
	}
	@Override
	public List<Map<String, Object>> getDepartZtree(TSUser user, String parentid) {
		Map para=new HashMap();
		String sql="select ID,DEPARTMENT_CODE,PARENT_ID,DEPART_NAME,(select count(1) from T_S_DEPART d3 where  d3.PARENT_ID=d.id) sub_Count ";
		sql=sql+ " from T_S_DEPART d where d.status='1'  ";
		if(!parentid.equals(""))
			sql=sql+" and d.PARENT_ID=#{parentid} ";
		else if(parentid==null||parentid.equals("")){
			String sqlCondition=dataruleService.genSqlByModuleName("authDept","d",user);
			String sq=sqlCondition.replaceAll("and","").replaceAll("\\(","").replaceAll("\\)","").replaceAll("1=1","").trim();
			if(sq.equals("")){
				sql=sql+" and (d.PARENT_ID='' or d.PARENT_ID is null) ";
			}else
				sql=sql+sqlCondition;
		}
		
		sql=sql+"  order by d.LEVEL_NO ";
		para.put("parentid", parentid);
		List<Map<String, Object>> deptList=commonService.findForJdbc(sql,para);
		return deptList;
	}
	
	@Override
	public List<Map<String, Object>> getDepartLevel(TSUser user, String parentid) {
		Map para=new HashMap();
		String sql="select LEVEL_NO from T_S_DEPART d where d.status='1'  ";
		if(!parentid.equals(""))
			sql=sql+" and d.PARENT_ID=#{parentid}";
		else
			sql=sql+" and (d.PARENT_ID='' or d.PARENT_ID is null) ";
		/*else if(isNeedCheck.equals("")||isNeedCheck.equals("0"))
			sql=sql+" and (d.PARENT_ID='' or d.PARENT_ID is null)";
		else if(isNeedCheck.equals("1")&&parentid.equals("")){
			parentid=deptId;
			//sql=sql+" and ((d.PARENT_ID=#{parentid} and exists (select 1 from from T_S_DEPART d1 where d1.status='1' and d1.IS_NEED_CHECK='1' and d1.PARENT_ID=#{parentid}))";
			sql=sql+" and d.PARENT_ID=#{parentid}";
		}*/
			
		String sqlCondition=dataruleService.genSqlByModuleName("authDept","d",user);
		sql=sql+sqlCondition;
		sql=sql+"  order by d.LEVEL_NO ";
		para.put("parentid", parentid);
		List<Map<String, Object>> deptList=commonService.findForJdbc(sql,para);
		return deptList;
	}
	@Override
	public List<Map<String, Object>> getAllDepartZtree(TSUser user, String parentid) {
		Map para=new HashMap();
		String sql="select ID,DEPARTMENT_CODE,PARENT_ID,DEPART_NAME,(select count(1) from T_S_DEPART d3 where  d3.PARENT_ID=d.id) sub_Count from T_S_DEPART d where d.status='1'  ";
		if(!parentid.equals(""))
			sql=sql+" and d.PARENT_ID=#{parentid}";
		else 
			sql=sql+" and (d.PARENT_ID='' or d.PARENT_ID is null) ";
		
		String sqlCondition=dataruleService.genSqlByModuleName("authDept","d",user);
		sql=sql+sqlCondition;
		sql=sql+"  order by d.LEVEL_NO ";
		para.put("parentid", parentid);
		List<Map<String, Object>> deptList=commonService.findForJdbc(sql,para);
		return deptList;
	}
}
